'use strict'
const UUID = require('uuid')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const config = require('./../../config/config')
module.exports = {

  /** 
   * @description: 设置token
   * @param { Object } user 用户信息
   */
  setToken: function(user) {
      const token = jwt.sign({
        'username': user.username,
        'create_time': user.create_time,
        '_id': user._id.toString()
      }, 
      config.secret,
      {
        expiresIn: config.expiresIn  // 过期时间
      })
      return token
  },

  /** 
   * @description: 验证token
   */
  verifyToken: function (token) {
    let result
    jwt.verify(token, config.secret, (err, data) => {
      // console.log(data)
      if (data) result = data
    })
    return result
  },

  /**
   * @description:  加密
   * @param { Object } params 用户信息
   */

  bcrypt: function (params) {
      return bcrypt.hash(params.password, 5)
  },

  /** 
   * @description: 解密
   * @param { Object } result 数据库返回的用户信息
   * @param { Object } user 请求接收的用户信息
   */

  compare: function (bodyPassword, resultPassword) {
      return bcrypt.compare(bodyPassword, resultPassword)
  },

  genUUID: function () {
    let uuid = null
    try {
        uuid = UUID.v1()
    } catch (error) {
        uuid = UUID.v4()
    }
    return uuid
  },

  /**
    * 解析字符串对象
    */
  jsonParse: function(str){
    try {
        return JSON.parse(str);
    } catch (err) {
        normalRequestErrorHandler(err);
        return str;
    }
  }
}
